<!--活动管理 - 新增/编辑活动-->
<template>
    <div class="rightCenter">
        <div class="editTop">
            <div class="editTopTitle" @click="cancelClick()">活动管理</div>
            <i class="icon font_family icon-yema-you"></i>
            <div class="editTopTitle">{{editVal}}</div>
        </div>
        <div class="editList">
            <div class="editListName">
                活动名称：
            </div>
            <input class="editListInpBox fontBlue" v-model.trim='titleVal' type="text" placeholder="标题不超过50个字" maxlength="50">
            <span class="warn" v-show='titleShow'>请输入名称</span>
        </div>
        <div class="editList">
            <div class="editListName">
                头图：
            </div>
            <div class="editUpImg">
                <div>
                    <div class="editUpImgHand" v-show='!handImgVal'>
                        <i class="icon font_family icon-shangchuanzhaopian"></i>
                    </div>
                    <img class="editHandImg" v-show='handImgVal' :src="handImgVal" alt="">
                </div>
                <div>
                    <label for="fileUpImg">
                        上传
                    </label>
                    <input id="fileUpImg" accept="image/jpeg,image/jpg,image/png,image/bmp,image/gif" type="file" v-on:change="upImgChange($event)">
                    <p :class="{fontGary:!imgFontShow,fontRed:imgFontShow}">（图片大小660*510像素）</p>
                </div>
                <div class="warn" v-show='imgupShow'>
                    请上传头图
                </div>
            </div>
        </div>
        <div class="editList">
            <div class="editListName">
                活动介绍：
            </div>
            <textarea id="textId" class="textBox" v-model.trim='briefVal' @input='textHeigth()' maxlength="200" placeholder="请输入200字以内的介绍"></textarea>
            <span class="warn" v-show='briefShow'>请输入200字以内的介绍</span>
        </div>
        <div class="editList">
            <div class="editListName">
                活动类型：
            </div>
            <div class="editListInpFont">
                <el-select v-model="typeVal" placeholder="请选择">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
            </div>
        </div>
        <div class="editList">
            <div class="editListName">
                问题列表：
            </div>
            <div class="issue">
                <li class="issueLi" v-for='(item,index) in issueList' :key='index'>
                    <input class="editListInpBox fontBlue" v-model='item.title' type="text" placeholder="请输入50字以内的问题" maxlength="50">
                    <div v-show='item.show' class="issueSelect" v-for='(iten,ind) in item.chide' :key='ind'>
                        <div class="issueTrue fontBlue">正确</div>
                        <div @click='issueCheckClick(index,ind)' class="issueCheck" :class="{checkBack:!iten.show,checkOkBack:iten.show}">
                            <div class="checkBor"></div>
                        </div>
                        <div class="isuueInd">
                            {{iten.num}}
                        </div>
                        <input class="editListInpBox issueInp fontBlue" v-model='iten.value' type="text" placeholder="请输入10个字以内的答案" maxlength="10">
                    </div>
                    <div class="issueButton">
                        <div v-show='!item.show && issueList.length > 1' class="buttonBox banckBlue" @click='unfoldClick(index)'>展 开</div>
                        <div v-show='item.show && issueList.length > 1' class="buttonBox banckBlue" @click='shutClick(index)'>折 叠</div>
                        <div v-show='issueList.length > 1' class="buttonBox banckRed" @click='delectClick(index)'>删 除</div>
                    </div>
                </li>
                <div v-show='issueList.length < 10' class="buttonBox addPrize" @click='addIssueClick()'>+添加题目</div>
            </div>
            <span class="warn" v-show='issueShow'>请完善问题列表</span>
        </div>
        <div class="editList">
            <div class="editListName">
                奖品配置：
            </div>
            <div class="prizeBox">
                <div class="prize" v-for='(item,index) in prizeList' :key='index'>
                    <div class="prizeTop">
                        <div :class="{prizeTopInd:true,yellowFont:index != 0,blueFont:index == 0}">
                            {{index | prizeTopIndFun}}
                        </div>
                        答对
                        <div class="prizeTopSelect">
                            <el-select v-model="item.num" placeholder="请选择">
                                <el-option v-for="item in item.numlist" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </div>
                        题
                    </div>
                    <div class="prizeFoot">
                        获得
                        <div class="prizeFootSelect">
                            <el-select v-model="item.id" placeholder="请选择">
                                <el-option v-for="item in item.idList" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </div>
                        共
                        <input class="prizeFootInp" type="text" v-model='item.prizeNum' oninput="value=value.replace(/[^0-9]/ig,'')"> 份
                    </div>
                </div>
                <div v-show='prizeList.length > 1' class="buttonBox prizeDelect" @click='prizeDelevtClick()'>
                    删除
                </div>
                <div v-show='prizeList.length < 5' class="buttonBox addPrize" @click='prizeAddClick()'>
                    +添加奖品
                </div>
            </div>
            <span class="warn" v-show='prizeShow'>请完善奖品配置</span>
        </div>
        <div class="editList">
            <div class="editListName">
                活动时间：
            </div>
            <div class="timeBox">
                <el-date-picker v-model="begin" type="datetime" placeholder="选择日期时间">
                </el-date-picker>
                至
                <el-date-picker v-model="finish" type="datetime" placeholder="选择日期时间">
                </el-date-picker>
            </div>
            <span class="warn" v-show='timeShow'>请选择正确的活动时间</span>

        </div>
        <div class="editList">
            <div class="editListName">
                规则说明：
            </div>
            <div class="explain">
                1.每个活动最多可以添加10个题目，每个题目只有4个答案选项；
                <br/> 2.奖品配置最多设置5等，等级默认按照答对题数多少从高到低排列；
                <br/> 3.若一等奖奖品被领完，但是有用户满足领一等奖奖品的条件，则按照先
                <br/> 后顺序领二等奖奖品，直到所有奖品发放完毕，活动自动结束。
            </div>
        </div>
        <div class="footButton">
            <div class="addBut" @click='addClick'>
                保 存
            </div>
            <div class="cancelBut" @click='cancelClick'>
                取 消
            </div>
        </div>
    </div>
</template>
<script>
import taskRequest from "../../assets/task";
import prizeRequest from "../../assets/prize";
import fileRequest from "../../assets/file";
export default {
  data() {
    return {
      editVal: "新增活动",
      titleVal: "", //名称
      titleShow: false,
      handImgVal: null, //头图
      imgupShow: false,
      imgFontShow: false, //头图限制文字
      briefVal: "", //活动介绍
      briefShow: false,
      typeVal: "11", //类型
      options: [
        { value: "11", label: "答题" }
        // { value: '22', label: '调查问卷' },
      ],
      issueList: [
        {
          title: "",
          chide: [
            { show: true, value: "", num: "A：" },
            { show: false, value: "", num: "B：" },
            { show: false, value: "", num: "C：" },
            { show: false, value: "", num: "D：" }
          ],
          show: true
        }
      ],
      issueShow: false,
      prizeList: [
        {
          num: "1",
          id: "",
          prizeNum: "",
          numlist: [{ value: "1", label: "1" }],
          idList: [
            { value: "1", label: "吹风机" },
            { value: "2", label: "笔记本" }
          ]
        }
      ],
      prizeShow: false,
      prizeCheckList: [], //可选奖品列表
      begin: "", //开始时间
      finish: "", //结束时间
      timeShow: false
    };
  },
  filters: {
    prizeTopIndFun: function(val) {
      if (val == 0) {
        return "一等奖";
      } else if (val == 1) {
        return "二等奖";
      } else if (val == 2) {
        return "三等奖";
      } else if (val == 3) {
        return "四等奖";
      } else if (val == 4) {
        return "五等奖";
      }
    }
  },
  created: function() {
    let self = this;
    if (sessionStorage.getItem("TABLIST")) {
      let arr = JSON.parse(sessionStorage.getItem("TABLIST"));
      let routShow = false;
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].name == "活动管理") {
          routShow = true;
        }
      }
      if (!routShow) {
        this.$router.push({
          path: "/login"
        });
        sessionStorage.clear();
        self.$message("暂无权限");
        return;
      }
    } else {
      this.$router.push({
        path: "/login"
      });
      sessionStorage.clear();
      self.$message("暂无权限");
      return;
    }
    this.searchFun();
    if (self.$route.query.button == "add") {
      self.editVal = "新增活动";
    } else {
      self.editVal = "编辑活动";
      taskRequest
        .promotionInfoFun({
          promotionId: self.$route.query.id
        })
        .then(data => {
          if (data.statusCode == 200) {
            self.titleVal = data.data.name;
            self.handImgVal = data.data.headShow;
            self.briefVal = data.data.desc;
            self.begin = data.data.startTime;
            self.finish = data.data.endTime;
            self.prizeList = data.data.awards;
            self.issueList = [];
            data.data.subjectsVo.forEach(ele => {
              self.issueList.push({
                title: ele.subject,
                options: ele.options,
                chide: [],
                show: true
              });
            });
            for (let i = 0; i < self.issueList.length; i++) {
              for (let j = 0; j < self.issueList[i].options.length; j++) {
                self.issueList[i].chide.push({
                  show: ele.show,
                  value: ele.value,
                  num: ele.num
                });
              }
            }
          } else {
            self.$message(data.statusMessage);
          }
        })
        .catch(msg => {
          self.$message("服务器异常");
        });
    }
  },
  watch: {},
  mounted() {},
  methods: {
    //奖品列表
    async searchFun(name = "") {
      let self = this;
      let params = {
        name: "",
        page: 1,
        size: 10000
      };
      let getParams = `name=${params.name}&page=${params.page}&size=${
        params.size
      }`;
      let res = await prizeRequest.getWebAwardPage(getParams);
      if (res.statusCode == 200) {
        if (res.data) {
          if (res.data.records) {
            self.prizeCheckList = [];
            res.data.records.forEach(ele => {
              self.prizeCheckList.push({
                value: ele.id,
                label: ele.name
              });
            });
            self.prizeList[0].idList = self.prizeCheckList;
          }
        }
      } else {
        self.$message(res.statusMessage);
      }
    },
    //活动管理
    cancelClick() {
      this.$router.push({
        path: "/home/activity"
      });
    },
    //text自动撑高
    textHeigth() {
      textId.style.height = 0;
      textId.style.height = textId.scrollHeight + "px";
    },
    //选择图片
    upImgChange(e) {
      let self = this;
      let files = e.target.files || e.dataTransfer.files;
      let fileData = files[0];
      let reader = new FileReader();
      reader.onload = function(e) {
        let data = e.target.result;
        let image = new Image();
        image.onload = function() {
          // if (image.width !== 600 || image.height !== 510) {
          //   self.imgFontShow = true;
          //   self.$message({
          //     type: "info",
          //     message: "上传图片尺寸不符，请重新上传"
          //   });
          //   document.getElementById("fileUpImg").value = "";
          // } else if (fileData.size > 1048576) {
          //   self.imgFontShow = true;
          //   self.$message({
          //     type: "info",
          //     message: "上传图片大小过大，请重新上传"
          //   });
          //   document.getElementById("fileUpImg").value = "";
          // } else {
          //   self.imgFontShow = false;
          //   self.uploadBanner(files[0]);
          // }
          self.uploadBanner(files[0]);
        };
        image.src = data;
      };
      reader.readAsDataURL(fileData);
    },
    //上传banner图片
    async uploadBanner(file) {
      let self = this;
      let formdata = new FormData();
      formdata.append("file", file);
      let res = await fileRequest.getfileUploadFile(formdata);
      if (res.statusCode == 200) {
        self.$message({
          message: "上传图片成功",
          type: "success"
        });
        self.handImgVal = res.data;
        document.getElementById("fileUpImg").value = "";
      } else {
        self.$message(res.statusMessage);
        self.dataList = [];
      }
    },
    //选择答案
    issueCheckClick(index, ind) {
      let self = this;
      for (let i = 0; i < self.issueList[index].chide.length; i++) {
        self.issueList[index].chide[i].show = false;
      }
      self.issueList[index].chide[ind].show = true;
    },
    //问题展开
    unfoldClick(index) {
      this.issueList[index].show = true;
    },
    //问题收起
    shutClick(index) {
      this.issueList[index].show = false;
    },
    //删除问题
    delectClick(index) {
      let self = this;
      if (self.issueList.length > 1) {
        let showVal = false;
        for (let i = 0; i < self.prizeList.length; i++) {
          if (self.issueList.length <= self.prizeList[i].num) {
            showVal = true;
          }
        }
        if (showVal) {
          self.$message("与奖品配置答对题目数冲突");
        } else {
          self.issueList.splice(index, 1);
          for (let i = 0; i < self.prizeList.length; i++) {
            self.prizeList[i].numlist = [];
          }
          for (let j = 0; j < self.prizeList.length; j++) {
            for (let i = 1; i < self.issueList.length + 1; i++) {
              self.prizeList[j].numlist.push({
                value: i,
                label: i
              });
            }
          }
        }
      }
    },
    //添加问题
    addIssueClick() {
      let self = this;
      if (self.issueList.length < 10) {
        self.issueList.push({
          title: "",
          chide: [
            { show: true, value: "", num: "A：" },
            { show: false, value: "", num: "B：" },
            { show: false, value: "", num: "C：" },
            { show: false, value: "", num: "D：" }
          ],
          show: true
        });
        for (let i = 0; i < self.prizeList.length; i++) {
          self.prizeList[i].numlist = [];
        }
        for (let j = 0; j < self.prizeList.length; j++) {
          for (let i = 1; i < self.issueList.length + 1; i++) {
            self.prizeList[j].numlist.push({
              value: i,
              label: i
            });
          }
        }
      }
    },
    //添加奖品配置
    prizeAddClick() {
      let self = this;
      if (this.prizeList.length < 5) {

        self.prizeList.push({
          num: "1",
          id: "",
          prizeNum: "",
          numlist: [{ value: "1", label: "1" }],
          idList: self.prizeCheckList
        });
      }
      for (let i = 0; i < self.prizeList.length; i++) {
        self.prizeList[i].numlist = [];
      }
      for (let j = 0; j < self.prizeList.length; j++) {
        for (let i = 1; i < self.issueList.length + 1; i++) {
          self.prizeList[j].numlist.push({
            value: i,
            label: i
          });
        }
      }
    },
    //删除奖品配置
    prizeDelevtClick() {
      if (this.prizeList.length > 1) {
        this.prizeList.splice(this.prizeList.length - 1, 1);
      }
    },
    //保存
    addClick() {
      let self = this;
      if (self.titleVal == "") {
        self.titleShow = true;
        return;
      } else {
        self.titleShow = false;
      }

      if (self.handImgVal == null) {
        self.imgupShow = true;
        return;
      } else {
        self.imgupShow = false;
      }

      if (self.briefVal == "") {
        self.briefShow = true;
        return;
      } else {
        self.briefShow = false;
      }
      let isShow = false;
      for (let i = 0; i < self.issueList.length; i++) {
        if (self.issueList[i].title == "") {
          isShow = true;
        }
        for (let j = 0; j < self.issueList[i].chide.length; j++) {
          if (self.issueList[i].chide[j].value == "") {
            isShow = true;
          }
        }
      }
      if (isShow) {
        self.issueShow = true;
        return;
      } else {
        self.issueShow = false;
      }

      let priShow = false;
      for (let i = 0; i < self.prizeList.length; i++) {
        if (self.prizeList[i].id == "") {
          priShow = true;
        }
        if (self.prizeList[i].prizeNum == "") {
          priShow = true;
        }
      }
      if (priShow) {
        self.prizeShow = true;
        return;
      } else {
        self.prizeShow = false;
      }

      if (self.begin == "" || self.finish == "") {
        self.timeShow = true;
        return;
      } else {
        if (self.finish - self.begin > 0) {
          self.timeShow = false;
        } else {
          self.timeShow = true;
          return;
        }
      }
      let awards = []; //奖品参数
      self.prizeList.forEach(ele => {
        awards.push({
          awardId: ele.id,
          count: ele.num,
          condition: ele.prizeNum
        });
      });
      let subjects = []; //问题参数
      for (let i = 0; i < self.issueList.length; i++) {
        subjects.push({
          subject: self.issueList[i].title,
          optionA: "",
          optionB: "",
          optionC: "",
          optionD: "",
          resultA: 0,
          resultB: 0,
          resultC: 0,
          resultD: 0
        });
      }
      for (let i = 0; i < self.issueList.length; i++) {
        for (let k = 0; k < subjects.length; k++) {
          if (k == i) {
            subjects[k].optionA = self.issueList[i].chide[0].value;
            subjects[k].optionB = self.issueList[i].chide[1].value;
            subjects[k].optionC = self.issueList[i].chide[2].value;
            subjects[k].optionD = self.issueList[i].chide[3].value;
            for (let j = 0; j < self.issueList[i].chide.length; j++) {
              if (self.issueList[i].chide[j].show == true) {
                if (j == 0) {
                  subjects[k].resultA = 1;
                } else if (j == 1) {
                  subjects[k].resultB = 1;
                } else if (j == 2) {
                  subjects[k].resultC = 1;
                } else if (j == 3) {
                  subjects[k].resultD = 1;
                }
              }
            }
          }
        }
      }
      let beginStr = self.begin.getTime(); //开始时间戳
      let finishStr = self.finish.getTime(); //结束时间戳
      let obj = {};
      if (self.$route.query.button == "add") {
        obj = {
          awards: awards, //奖品
          subjects: subjects, //问题
          desc: self.briefVal, //介绍
          startTime: beginStr, //开始时间
          endTime: finishStr, //结束时间
          headShow: self.handImgVal, //图片
          name: self.titleVal //活动名称
        };
      } else {
        obj = {
          awards: awards, //奖品
          subjects: subjects, //问题
          desc: self.briefVal, //介绍
          startTime: beginStr, //开始时间
          endTime: finishStr, //结束时间
          headShow: self.handImgVal, //图片
          name: self.titleVal //活动名称
        };
      }
      taskRequest
        .promotionSaveFun(JSON.stringify(obj))
        .then(data => {
          if (data.statusCode == 200) {
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            this.$router.push({
              path: "/home/activity"
            });
          } else {
            self.$message(data.statusMessage);
          }
        })
        .catch(msg => {
          self.$message("服务器异常");
        });
    }
  }
};
</script>
<style scoped>
.editUpImgHand {
  width: 200px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  background: #f2f5f7;
  color: #b2b7c0;
}

.editUpImgHand i {
  font-size: 20px;
}

.textBox {
  width: 350px;
  min-height: 80px;
  line-height: 24px;
  font-size: 14px;
  background: #f2f5f7;
  margin-left: 12px;
  padding: 4px 8px;
  margin-right: 14px;
  resize: none;
}

.editHandImg {
  width: 330px;
  height: 255px;
}

.issue {
  width: 450px;
}

.issueSelect {
  display: flex;
  margin: 12px;
}

.issueTrue {
  height: 40px;
  line-height: 40px;
}

.issueCheck {
  margin: 10px;
}

.isuueInd {
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  color: #000;
}

.issueInp {
  width: 230px !important;
  height: 40px !important;
}

.issueButton {
  display: flex;
  margin: 12px;
}

.fontBlue {
  color: #2f3a5d;
  font-size: 14px;
  font-weight: bold;
}

.banckBlue {
  background: #279de2;
}

.banckRed {
  background: #ed4a47;
  margin: 0 24px;
}

.prizeDelect {
  background: #ed4a47;
  margin: 0 12px;
}

.prizeBox {
  width: 450px;
  padding: 4px 8px;
}

.prize {
  margin-bottom: 14px;
}

.prizeFoot {
  margin-top: 14px;
}

.prizeFoot,
.prizeTop {
  display: flex;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  color: #2f3a5d;
}

.prizeTopInd {
  margin-right: 14px;
}

.prizeTopSelect {
  margin: 0 14px;
}

.prizeFootSelect {
  margin: 0 14px;
}

.prizeFootInp {
  width: 60px;
  height: 40px;
  margin: 0 14px;
  padding: 0 5px;
  background: #f2f5f7;
}

.addPrize {
  width: 110px;
  height: 40px;
  font-size: 16px;
  line-height: 40px;
  text-align: center;
  cursor: pointer;
  background: #279de2;
  margin: 14px;
}

.explain {
  font-size: 14px;
  padding: 14px 8px;
  line-height: 24px;
  color: #2f3a5d;
  font-weight: bold;
}

.timeBox {
  display: flex;
  height: 40px;
  line-height: 40px;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  margin-top: 10px;
  color: #2f3a5d;
}

.footButton {
  display: flex;
  width: 700px;
  align-items: center;
  margin-top: 124px;
  margin-left: 230px;
}

.addBut {
  width: 150px;
  height: 50px;
  border-radius: 25px;
  text-align: center;
  line-height: 50px;
  cursor: pointer;
  margin: 0 12px;
  background: #279de2;
  color: white;
}

.cancelBut {
  width: 150px;
  height: 50px;
  border-radius: 25px;
  text-align: center;
  line-height: 50px;
  cursor: pointer;
  margin: 0 12px;
  border: 1px solid #279de2;
  color: #279de2;
}
</style>